# -*- coding: utf-8 -*-
# Create your views here.
import logging
from com.jumang.util.SiteHelper import render_jum_response,verify_required
from django.template.context import RequestContext
import os
from django.http import HttpResponse,HttpResponseNotModified
import datetime
from google.appengine.ext import db
from com.jumang.model import note
from com.jumang.model import uploadfile,uploadpicture
from django.http import HttpResponsePermanentRedirect
from django.http import HttpResponse
from com.jumang.model.message import message
from google.appengine.api import users
from com.jumang.model.Tag import Tag
from com.jumang.model.NoteCategory import NoteCategory
from com.jumang.model.NoteTag import NoteTag
from com.jumang.model.FileCategory import FileCategory,PictureCategory
from com.jumang.model.comment import notecomment,filecomment,pictureComment
import sys
from config import JumConfig,realConfig
from appengine_django.core.paginator import Paginator,Page
from appengine_utilities.sessions import Session
from mimetypes import types_map
from google.appengine.api import memcache
import urllib


def verify(request):
  template_values={}
  template_values['unchecked']='True'
  initPublicInfo(request,template_values)
  return render_jum_response(request,'verifymain.html',template_values)

def home(request):
  currentHome=u'http://'+request.environ['HTTP_HOST']+'/'
  if currentHome==realConfig.resourceHome:
    return downloads(request)
  elif currentHome==realConfig.albumHome:
    return albums(request)
  elif currentHome==realConfig.privateHome:
    return albums(request)
  else:
    ## todo home page
    return notes(request)

def getMessages(count):
    query=db.Query(message)
    query.order('-createTime')
    result=query.fetch(count)
    return result

def initPublicInfo(request,template_values):
    if template_values:
        template_values['messages']=getMessages(5)
    else:
        template_values={'messages':getMessages(5)}
    realConfig.currentHome=u'http://'+request.environ['HTTP_HOST']+'/'
    template_values['config']=realConfig
    tags=Tag.all()
    result=tags.fetch(1000)
    result.sort()
##    result.reverse()
    template_values['tags']=result[:17]
    
    template_values['noteComments']=notecomment.all().order('-createTime').fetch(5)
    template_values['fileComments']=filecomment.all().order('-createTime').fetch(5)
    template_values['pictureComments']=pictureComment.all().order('-createTime').fetch(5)

def checkPage(request,dataSet):
    paginator=Paginator(dataSet,realConfig.pageSize)
    try:
        pageNum=int(request.GET['page'])
    except:
        pageNum=1
    if pageNum>paginator.num_pages:
        pageNum=paginator.num_pages
    if pageNum<1:
        pageNum=1
    page=paginator.page(pageNum)
    return page
    
def notes(request):
#    logging.warning("main page")
    date=datetime.datetime.now()
    template_values = {}

    try:
        temp=request.GET['skip']
        skip=True
    except:
        skip=False
## check date for special day        
    if not skip:
        if (date.month==5 and date.day >2 and date.day <6):
            return render_jum_response(request,'myson.html')
      
        if (date.month==11 and date.day >7 and date.day <11):
          return render_jum_response(request,'mywife.html')

        if (date.month==8 and date.day >28 and date.day <32):
          return render_jum_response(request,'marriage.html')

##        if(date.month==8 and date.day >5 and date.day <8):
##          return render_jum_response(request,'qixi.html')

## view category notes
    
    if request.GET.__contains__('category'):
      categoryId=request.GET['category']
      category=NoteCategory.get_by_id(int(categoryId))
  ##        logging.warning(category)
      result=category.note_set
      result.order('-createTime')
      result.filter('isPublic',True)
    elif request.GET.__contains__('tag'):
      tagId=request.GET['tag']
      inTag=Tag.get_by_id(int(tagId))
      result=[]
      for notetag in inTag.notetag_set:
          if notetag.note.isPublic:
              result[0:0]=[notetag.note]
    else:
  ##            logging.warning(sys.exc_info()[0])
        query=db.Query(note.note)
        query.filter('isPublic',True)
        query.order('-createTime')
        page=checkPage(request,query)
        result=page.object_list
        template_values['page']= page
    
    template_values['data']= result
    
    categories=NoteCategory.all()
    template_values['categories']=categories

    initPublicInfo(request,template_values)

    return render_jum_response(request,'notemain.html',template_values)

##    path = os.path.join(os.path.dirname(__file__), 'AddNote.html')
##    logging.warning(path)
##    #self.response.out.write(template.render(path, template_values))
##    return HttpResponse(template.render(path, template_values))
##    
def downloads(request):
    logging.warning("download main page")
    template_values = {}

    if request.GET.__contains__('category'):
        categoryId=request.GET['category']
        category=FileCategory.get_by_id(int(categoryId))
        result=category.file_set
        result.filter('isPublic',True)
        result.order('-createTime')
    else:
        query=db.Query(uploadfile.file)
        query.order('-createTime')
        query.filter('isPublic',True)
        page=checkPage(request,query)
        result=page.object_list
        template_values['page']= page

    template_values['data']= result

    categories=FileCategory.all()
    template_values['categories']=categories

    initPublicInfo(request,template_values)

    return render_jum_response(request,'downloadmain.html',template_values)
  
def download(request):
    logging.warning("download main page")
    template_values = {}
  
    myfile=uploadfile.file.get_by_id(int(request.GET['id']))
    if not myfile.isPublic:
        return HttpResponsePermanentRedirect('/')
      
    response=HttpResponse(myfile.content,mimetype='application/octet-stream')
    response['Content-Disposition'] ='attachment; filename=%s' % myfile.name.encode('utf-8')
  
    return response

  
def about(request):
    logging.warning("about page")
    template_values={}
    initPublicInfo(request,template_values) 
    return render_jum_response(request,'about.html',template_values)

def isAdmin(template_values):
    user = users.get_current_user()
    if user:
      if users.is_current_user_admin():
          template_values['admin']="true"


def getnoteinf(request):
    myNote=note.note.get_by_id(int(request.GET['id']))
    if not myNote.isPublic:
        return HttpResponsePermanentRedirect('/')
    template_values = {'note': myNote}
    isAdmin(template_values)
    initPublicInfo(request,template_values)
    return render_jum_response(request,'noteview.html',template_values)

def getfileinf(request):
    myfile=uploadfile.file.get_by_id(int(request.GET['id']))
    if not myfile.isPublic:
        return HttpResponsePermanentRedirect('/')
    template_values = {'file': myfile}
    isAdmin(template_values)
    initPublicInfo(request,template_values)
    return render_jum_response(request,'fileview.html',template_values)
  
def messages(request):
    template_values = {'data': getMessages(100)}
    isAdmin(template_values)
    initPublicInfo(request,template_values)
    return render_jum_response(request,'messagemain.html',template_values)

@verify_required
def albums(request):
  logging.warning("albums main page")
  template_values = {}
  
  if request.GET.__contains__('category'):
      categoryId=request.GET['category']
      category=PictureCategory.get_by_id(int(categoryId))
      result=category.picture_set
      result.filter('isPublic',True)
      result.order('-createTime')
  else:
      query=db.Query(uploadpicture.Picture)
      query.order('-createTime')
      query.filter('isPublic',True)
      page=checkPage(request,query)
      result=page.object_list
      template_values['page']= page
  
  template_values['data']= result
  
  categories=PictureCategory.all()
  template_values['categories']=categories
  
  initPublicInfo(request,template_values)
  
  return render_jum_response(request,'albummain.html',template_values)
  


@verify_required
def getPictureInf(request):
    myfile=uploadpicture.Picture.get_by_id(int(request.GET['id']))
    if not myfile.isPublic:
        return HttpResponsePermanentRedirect('/')
    template_values = {'file': myfile}
    isAdmin(template_values)
    initPublicInfo(request,template_values)
    return render_jum_response(request,'pictureview.html',template_values)

@verify_required  
def getPicture(request):
    logging.warning("download picture")
    template_values = {}
  
    myfile=uploadpicture.Picture.get_by_id(int(request.GET['id']))
    if not myfile.isPublic:
        return HttpResponsePermanentRedirect('/')
    
    #logging.warning(request.GET['if_modified_since'])
    if request.environ.__contains__('HTTP_IF_MODIFIED_SINCE'):
      #logging.warning("do not download picture")
      response=HttpResponseNotModified()
    
    else:
      ext = os.path.splitext(myfile.name)[1]
      if ext:
        ext=ext.lower()
      if types_map.has_key(ext):
        mime_type = types_map[ext]
      else:
        mime_type = 'application/octet-stream'
#      logging.warning(ext)
#      logging.warning(mime_type)
      response=HttpResponse(myfile.content,mimetype=mime_type)
      response['Content-Disposition'] ='inline; filename=%s' % myfile.name.encode('utf-8')
      response.headers['Date'] = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
      response.headers['Last-Modified'] = myfile.createTime.strftime('%a, %d %b %Y %H:%M:%S GMT')
      response.headers['Cache-Control'] = 'max-age=%d' % 3600
      response.headers['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)).strftime('%a, %d %b %Y %H:%M:%S GMT')
  
    return response

def config(request):
    reponse=HttpResponse()
    reponse.write(realConfig.getLinks(request))
    return reponse
